const state = {
    tab: [], // 已经缓存过的标签
    visited: []
}

const mutations = {
    ADD_VISITED(state, payload) {
        const index = state.visited.findIndex(visit => visit === payload);
        if(index < 0) {
            state.visited.push(payload);
        }
    },
    DEL_VISITED(state, payload) {
        const index = state.visited.findIndex(visit => visit === payload);
        if(index >= 0) {
            state.visited.splice(index, 1)
        }
    },
    ADD_TAB(state, payload) {
        // ! 先判断visited中是否存在已有路由 如果有的话就不新增
        if(state.visited.some(visit => visit === payload)){
            return;
        }
        state.visited.push(payload);
        const index = state.tab.findIndex(t => t.name === payload);
        if(index >= 0) {
            state.tab[index].key++;
        } else {
            state.tab.push({
                name: payload,
                key: 0
            });
        }
    },
    DEL_TAB(state, payload) {
        if(state.visited.some(visit => visit === payload)){
            const index = state.visited.findIndex(visit => visit === payload);
            if(index >= 0) {
                state.visited.splice(index, 1)
            }
        }
        const index = state.tab.findIndex(t => t.name === payload);
        if(index >= 0) {
            state.tab[index].key++;
        }
    }
}

const actions = {
    addTab({commit}, payload) {
        commit('ADD_TAB', payload)
    },
    delTab({commit}, payload) {
        commit('DEL_TAB', payload)
    },
    addVisited({commit}, payload) {
        commit('ADD_VISITED', payload)
    },
    delVisited({commit}, payload) {
        commit('DEL_VISITED', payload)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
  